<template>
  <Dialog
    :title="dialogTitle"
    v-model="codeKeyboardConfig.dialogVisible"
    :width="width"
    append-to-body
    :top="'5vh'"
    :show-close="props.showClose"
    :before-close="handleClose"
  >
    <div class="codeKey-box-top">
      <div class="custom-text-24" v-if="inputType == 'password'"> 请输入您的六位密码 </div>
      <div class="custom-text-24" v-if="inputType == 'text'">
        请输入您 {{ phoneFormat(mobile) }}的验证码
      </div>
      <div class="flex w-full mt-20px" style="justify-content: space-between">
        <div v-for="(pw, index) in passwords" :key="index">
          <el-input
            :controls="false"
            :max="9"
            :type="inputType"
            autocomplete="new-password"
            class="password-input custom-text-44"
            ref="elInputRef"
            v-model="pw.value"
            :min="0"
            :maxlength="1"
            @input="(value: any) => handleInput(index, value)"
          />
        </div>
      </div>
      <!-- 这个代码不能删 删了会导致输入顺序改变 具体原因未知 -->
      <div class="flex w-full mt-20px" v-show="false">
        <el-input
          class="password-input custom-text-44"
          :maxlength="6"
          v-model="codeKeyboardConfig.keyboardValue"
          :type="inputType"
        />
      </div>
    </div>
    <div class="flex mt-20px" style="justify-content: space-between">
      <div
        class="custom-text-26 c-[var(--el-color-primary)]! cursor-pointer"
        @click="getSmsCode"
        v-if="inputType == 'password'"
      >
        验证码认证
      </div>
      <div
        class="custom-text-26 c-[var(--el-color-primary)]! cursor-pointer"
        v-if="inputType == 'text'"
        @click="getPasswordCode"
      >
        密码认证
      </div>
      <div v-if="inputType == 'text'">
        <span
          v-if="sendAuthCode"
          class="custom-text-26 c-[var(--el-color-primary)]! cursor-pointer"
          @click="sendSms()"
          >获取验证码</span
        >
        <span v-if="!sendAuthCode" class="custom-text-26 c-[var(--el-color-primary)]!"
          ><span class="auth_text_blue">{{ auth_time }}</span
          >s</span
        >
      </div>
      <!-- <div class="font26 c-[var(--el-color-primary)]! cursor-pointer">
        忘记密码?
      </div> -->
    </div>
    <div class="mt-20px digitKeyboard-password-box" v-if="codeKeyboardConfig.dialogVisible">
      <DigitKeyboard ref="DigitKeyboardRef" v-model="codeKeyboardConfig.keyboardValue" />
    </div>
  </Dialog>
</template>
<script setup lang="ts" name="codeKeyboardDialog">
/**密码输入弹框 */
import { ref, defineAsyncComponent, watch, nextTick } from 'vue'
import { storeToRefs } from 'pinia'

/** 门店会员信息 */
import { useShopUserStoreWithOut } from '@/store/modules/shop/user'
const shopUserStore = useShopUserStoreWithOut()
const mobile = computed(() => {
  return shopUserStore.getUser.mobile
})
import { phoneFormat } from '@/utils/formatter'

const DigitKeyboard = defineAsyncComponent(() => import('./digitKeyBoard.vue'))
const dialogTitle = ref('') // 弹窗的标题
const width = ref('450px') //宽度

import { ElMessageBox } from 'element-plus'
import { propTypes } from '@/utils/propTypes'

import * as ConfigApi from '@/api/shop/system/config/index'

/** 密码键盘信息 */
import { useShopKeyboardWithOut } from '@/store/modules/shop/keyBoard'
const shopKeyboard = useShopKeyboardWithOut()
const { codeKeyboardConfig } = storeToRefs(shopKeyboard)
const DigitKeyboardRef = ref()
const inputType = ref('password')
const passwords = ref([
  { value: '' },
  { value: '' },
  { value: '' },
  { value: '' },
  { value: '' },
  { value: '' }
])
const props = defineProps({
  showClose: propTypes.bool.def(false)
})

const emit = defineEmits(['handleOperation', 'handleConfirm'])

const handleClose = async (done: () => void) => {
  ElMessageBox.confirm('是否取消输入密码?', '提示', {
    confirmButtonText: '确认取消',
    cancelButtonText: '继续输入',
    type: 'warning'
  })
    .then(() => {
      done()
    })
    .catch(() => {})
}
// const state = reactive({
//   digitKeyboardValue: ""
// })
const handleOpend = () => {
  if (DigitKeyboardRef.value) {
    DigitKeyboardRef.value.handleClear()
  }
}
watch(
  () => codeKeyboardConfig.value.dialogVisible,
  () => {
    if (codeKeyboardConfig.value.dialogVisible) {
      handleOpend()
    }
  }
)
watch(
  () => codeKeyboardConfig.value.keyboardValue,
  () => {
    let passwordStr = codeKeyboardConfig.value.keyboardValue.split('')
    passwords.value = [
      { value: '' },
      { value: '' },
      { value: '' },
      { value: '' },
      { value: '' },
      { value: '' }
    ]
    passwordStr.forEach((ele, index) => {
      passwords.value[index].value = ele
    })
    if (codeKeyboardConfig.value.keyboardValue.length == 6) {
      handleConfirm()
    }
  }
)

const elInputRef = ref()
// 输入框失去焦点时触发
const handleInput = (index: number, value: any) => {
  // 自动跳到下一个输入框
  if (value && index < passwords.value.length - 1) {
    // 使用nextElementSibling跳转到下一个InPut框（相当于tab键进入下一个输入框）
    const nextInput = elInputRef.value[index + 1]
    if (nextInput) {
      nextTick(() => {
        nextInput.focus()
      })
    }
  }
  let password = passwords.value.map((item) => item.value).join('')
  codeKeyboardConfig.value.keyboardValue = password
  if (codeKeyboardConfig.value.keyboardValue.length == 6) {
    // handleConfirm()
  }
}

const handleConfirm = () => {
  emit('handleConfirm')
} //确定
const sendAuthCode = ref(true)
const auth_time = ref(0)
const auth_timetimer = ref()
const getSmsCode = () => {
  codeKeyboardConfig.value.keyboardValue = ''
  inputType.value = 'text'
  sendSms()
}
const sendSms = () => {
  let phone = mobile.value
  if (sendAuthCode.value) {
    ConfigApi.sendSmsCode({ mobile: phone, scene: 22 }).then(() => {
      auth_time.value = 60
      sendAuthCode.value = false
      auth_timetimer.value = setInterval(() => {
        auth_time.value--
        if (auth_time.value <= 0) {
          sendAuthCode.value = true
          clearInterval(auth_timetimer.value)
        }
      }, 1000)
    })
  }
}
const getPasswordCode = () => {
  codeKeyboardConfig.value.keyboardValue = ''
  inputType.value = 'password'
}
</script>
<style lang="scss" scoped>
.codeKey-box {
  display: flex;
  flex-direction: column;
}

.digitKeyboard-password-box {
  height: 100%;
}

.codeKey-box-top {
  display: flex;
  flex-direction: column;

  .flex-item {
    margin-right: 20px;
    border-radius: 4px;

    &:last-child {
      margin-right: 0px;
    }
  }
}

.password-input {
  height: 69.67px;
  width: 100%;

  :deep(.el-input__wrapper) {
    border-radius: 4px;
  }

  :deep(.el-input__inner) {
    --el-input-inner-height: 48px;
    text-align: center;
    color: var(--el-color-primary);
  }
}
</style>
